package com.hzp.tool.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class ConfigUtils {

    public static File getConfigFile(Class<?> clazz) {
        File directory = new File("conf/");
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IllegalStateException("创建配置文件目录失败：" + directory);
        }
        String packageName = clazz.getPackage().getName().replace('.', '_');
        String className = clazz.getSimpleName();
        return new File(directory, packageName + "_" + className + ".properties");
    }

    public static Properties readConfig(Class<?> clazz) {
        Properties properties = new Properties();
        File file = getConfigFile(clazz);
        if (file.exists()) {
            try (InputStream input = new FileInputStream(file)) {
                properties.load(input);
            } catch (Exception e) {
                throw new IllegalStateException("读取配置文件失败：" + e.getMessage());
            }
        }
        return properties;
    }

    public static void saveConfig(Class<?> clazz, Properties properties) {
        try (OutputStream output = new FileOutputStream(getConfigFile(clazz))) {
            properties.store(output, "");
        } catch (Exception e) {
            throw new IllegalStateException("保存配置文件失败：" + e.getMessage());
        }
    }
}
